//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.Collections.ObjectModel;
using Microsoft.Research.ScientificWorkflow.TridentUtilities;
using SR = Microsoft.Research.DataLayer;

namespace Microsoft.Research.ScientificWorkflow.TridentComposer
{
    /// <summary>
    /// Proxy class which imports a workflow in a separate appdomain
    /// </summary>
    public class ImportWorkflowProxy : MarshalByRefObject
    {
        #region private fields
        private Collection<FileReference> fileReferences;
        private SR.Connection registryConnection;
        private WorkflowProperties workflowDetails;
        private string userName;
        #endregion

        #region Constructors
        /// <summary>
        ///  Dummy constructor. Needed to create this object by CreateInstanceAndUnWrap method.
        /// </summary>
        public ImportWorkflowProxy()
        {
        }

        /// <summary>
        /// Initializes a class which creates a new appdomain to import workflows.
        /// </summary>
        /// <param name="workflowDetails">The workflow details.</param>
        /// <param name="fileReferences">The file references.</param>
        /// <param name="registryConnection">The registry connection.</param>
        /// <param name="userName">The user name.</param>
        public ImportWorkflowProxy(WorkflowProperties workflowDetails,
            Collection<FileReference> fileReferences,
            SR.Connection registryConnection, string userName)
        {
            this.workflowDetails = workflowDetails;
            this.fileReferences = fileReferences;
            this.registryConnection = registryConnection;
            this.userName = userName;
        }
        #endregion

        #region Public methods
        /// <summary>
        /// Import the workflow.
        /// </summary>
        /// <returns>True if the import is successful;False otherwise.</returns>
        public Guid Execute()
        {
            AppDomain childAppdomain = null;
            try
            {
                childAppdomain = this.CreateAppDomain();
                
                ImportWorkflowProxy importProxy = childAppdomain.CreateInstanceAndUnwrap
                     ("Microsoft.Research.ScientificWorkflow.TridentComposer",
                     "Microsoft.Research.ScientificWorkflow.TridentComposer.ImportWorkflowProxy") as ImportWorkflowProxy;
                importProxy.Init(this.workflowDetails, this.registryConnection, this.fileReferences, this.userName);
                return importProxy.ImportWorkflow();
            }
            finally
            {
                UnloadAppDomain(childAppdomain);
            }
        }
        #endregion

        #region private methods
        /// <summary>
        /// Import the workflow.
        /// </summary>
        private Guid ImportWorkflow()
        {
            ActivityComposer activityComposer = new ActivityComposer(this.registryConnection, false);
            WorkflowComposer composer = new WorkflowComposer(this.registryConnection, activityComposer);
            return composer.ImportWorkflow(this.fileReferences, workflowDetails, userName, false);
        }

        /// <summary>
        /// Initializes the proxy object in a different appdomain.
        /// </summary>
        /// <param name="workflowDetails">The workflow details.</param>
        /// <param name="fileReferences">The file references.</param>
        /// <param name="registryConnection">The registry connection.</param>
        /// <param name="userName">The user name.</param>
        private void Init(WorkflowProperties details,
            SR.Connection registryConnection,
            Collection<FileReference> fileReferences,
            string userName)
        {
            this.workflowDetails = details;
            this.registryConnection = registryConnection;
            this.fileReferences = fileReferences;
            this.userName = userName;

            SR.SR_Connection.Init();
            this.registryConnection.Open();
            this.registryConnection.AutoSave = false;

            // Authenticate the user.
            try
            {
                TridentAuthentication authenticate = new TridentAuthentication(this.registryConnection);
                authenticate.AuthenticateUser();
            }
            catch (TridentCustomException)
            {
                throw;
            }
        }

        /// <summary>
        /// Creates a new app domain.
        /// </summary>
        /// <returns>New instance of the app domain.</returns>
        private AppDomain CreateAppDomain()
        {
            AppDomain newDomain = AppDomain.CreateDomain("ImportActivityAppdomain");
            newDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException);
            return newDomain;
        }

        /// <summary>
        /// Unloads the app domain.
        /// </summary>
        /// <param name="appDomain">Instance of the AppDomain.</param>
        private static void UnloadAppDomain(AppDomain appDomain)
        {
            if (appDomain != null)
            {
                AppDomain.Unload(appDomain);
            }
        }

        /// <summary>
        /// Method logs the unhandled exception in the app domain.
        /// </summary>
        /// <param name="sender">Object who raises the unhandled exception.</param>
        /// <param name="e">Event argument containing exception details.</param>
        private void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // No-op.
        }
        #endregion
    }
}
